import { ILoadMapTypeAll, ISearchTranslateAll } from '@/common';
import { ManageCommonAPI } from '@/pages/type';
import { commonManageSearchParams, getLoadMapList, getTenantID, requestFunComponFiex } from '@/utils';
import { useRequest } from 'umi';
import { getManageTabSwitch, getSearchChild, getSearchList } from '../mconfig';
import { useMemo, useState } from 'react';
import { getBaseUrl } from '@/services/urlconst';
import { openContractSubjectManage } from './UpdateTableService';
import moment from 'moment';

const baseUrl = getBaseUrl();
// const baseUrl = 'http://192.168.153.246:31019'; //旭潮本地

const contractManageService = (curRes: Record<string, any>, pageParams: Record<string, any> | null) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, //合同类型
    `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`, //采购方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`, //合同状态
    `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}`, //支付方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`, //作废方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`, //币种
  ];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /**获取权限参数 */
  let queryTypeObj: Record<string, any> = getManageTabSwitch(curRes, pageParams);

  /** 获取合同主体数据 */
  const { dataList } = openContractSubjectManage(curRes, true);

  /** 获取搜索参数 */
  const searchListParams = getSearchList(loadMdicMapObj?.loadMapInfo, queryTypeObj, dataList, pageParams);

  /** 保存全部搜索参数 */
  const [allSearchParams, setAllSearchParams] = useState<Record<string, any>>({});

  /** 获取列表数据  */
  const { tableProps, data, loading, run, refresh } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      let requestBody: Record<string, any> = {
        ...queryTypeObj,
        current: 1,
        pageSize: 10,
        sort: 'changeFlag asc, createTime',
        order: 'desc',
        dicTypeIds: loadMdicIds?.toString(),
        state: pageParams?.state?.toString(),
        ...opt,
      };
      if (pageParams && pageParams?.manageTreeTable) {
        requestBody['changeFlag'] = 0;
      }

      if (pageParams?.oversightBtnDom) {
        //督办进入
        requestBody['sealTimeEnd'] = moment()?.subtract(30, 'days')?.format('YYYY-MM-DD HH:mm:ss');
      }

      const searchParams: Record<string, any> = commonManageSearchParams(searchListParams, requestBody, {
        dicTransName: 'supplyKind,supplyType,procureReal,changeTypeName,state,payStyle,cancelType,checkState,procureOrg,businessType,currencyType',
        orgTransName: `${ISearchTranslateAll.SIGN_DEPT},${ISearchTranslateAll.CREATER_DEPT},${ISearchTranslateAll.OWNER_DEPT},${ISearchTranslateAll.CANCEL_DEPT},${ISearchTranslateAll.DUTY_DEPT},${ISearchTranslateAll.HAND_DEPT}`,
        // areaTransName: `${ISearchTranslateAll.AREA_TRANS}`,
      });
      setAllSearchParams(searchParams);
      // const requestURL = `${baseUrl}/contractController/dataGrid/${requestBody?.params}`;
      let requestURL = `${baseUrl}/contractController/dataGrid/${requestBody?.params}`;

      //如果是草稿，始终是ownerId
      if (pageParams?.state?.toString() == `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1000`) {
        requestURL = `${baseUrl}/contractController/dataGrid/ownerID`;
      }

      return requestFunComponFiex('POST', requestURL, searchParams);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /* 获取页面数据 */
  const getContractData = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    if (request?.ownTime) {
      const [ownTimeStart, ownTimeEnd] = request.ownTime;
      request['ownTimeStart'] = ownTimeStart.format('YYYY-MM-DD 00:00:00');
      request['ownTimeEnd'] = ownTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['ownTime'];
    }

    if (request?.cancelTime) {
      const [cancelTimeStart, cancelTimeEnd] = request.cancelTime;
      request['cancelTimeStart'] = cancelTimeStart.format('YYYY-MM-DD 00:00:00');
      request['cancelTimeEnd'] = cancelTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['cancelTime'];
    }

    if (request?.preTime) {
      const [preBeginTime, preFinishTime] = request.preTime;
      request['preBeginTime'] = preBeginTime.format('YYYY-MM-DD 00:00:00');
      request['preFinishTime'] = preFinishTime.format('YYYY-MM-DD 23:59:59');
      delete request['preTime'];
    }

    if (request?.realTime) {
      const [realBeginTime, realFinishTime] = request.realTime;
      request['realBeginTime'] = realBeginTime.format('YYYY-MM-DD 00:00:00');
      request['realFinishTime'] = realFinishTime.format('YYYY-MM-DD 23:59:59');
      delete request['realTime'];
    }

    delete request['createFormNameDept'];
    delete request['createFormNameUser'];
    if (request?.createrID && request?.createrID?.length > 0) {
      request['createrID'] = request?.createrID?.toString();
    } else {
      delete request['createrID'];
    }

    run({
      ...request,
    });
  };

  /** 搜索列表  */
  const searchList = useMemo(() => {
    return {
      searchList: searchListParams,
    };
  }, [loadMdicMapObj?.loadMapInfo]);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  return {
    loading,
    getContractData,
    reloadRefresh: refresh,
    allSearchParams,
    ...returnTableProps,
    ...searchList,
  };
};

/** 获取子合同数据 */
const contractChildervice = (callback: (res: any) => void) => {
  /**  需要获取的数据字典 */
  const loadMdicIds: string[] = [
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}`, //合同状态
    `${getTenantID()}${ILoadMapTypeAll.PAYMENT_STYLE}`, //支付方式
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`, //合同作废类型
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_TYPE}`, //合同类型
    `${getTenantID()}${ILoadMapTypeAll.CONTRACT_CURRENCYTYPE}`, //币种
  ];

  /** 获取数据字典loadMdicMap */
  const loadMdicMapObj: Record<string, any> = getLoadMapList(loadMdicIds);

  /** 获取搜索参数 */
  const searchListParams = getSearchChild(loadMdicMapObj?.loadMapInfo);

  /** 获取列表数据  */
  const { tableProps, data, loading, run } = useRequest(
    (opt: ManageCommonAPI.IGridRequestType) => {
      const requestBody: Record<string, any> = {
        // ...queryTypeObj,
        current: 1,
        pageSize: 999,
        sort: 'createTime',
        order: 'desc',
        dicTypeIds: loadMdicIds?.toString(),
        ...opt,
      };

      const searchParams: Record<string, any> = commonManageSearchParams(searchListParams, requestBody, {
        dicTransName: 'supplyKind,supplyType,procureReal,state,payStyle,cancelType,currencyType',
        orgTransName: `${ISearchTranslateAll.SIGN_DEPT},${ISearchTranslateAll.CREATER_DEPT},${ISearchTranslateAll.OWNER_DEPT},${ISearchTranslateAll.CANCEL_DEPT}`,
        // areaTransName: `${ISearchTranslateAll.AREA_TRANS}`,
      });

      const requestURL = `${baseUrl}/contractController/getMcontractChild`;
      return requestFunComponFiex('POST', requestURL, searchParams);
    },
    {
      manual: true, //页面初始请求为 true
      paginated: true,
      defaultPageSize: 999,
      onSuccess: callback,
    },
  );

  /* 获取页面数据 */
  const getChildManage = (otherRequest: ManageCommonAPI.IGridRequestType | any) => {
    const request: ManageCommonAPI.IGridRequestType | any = {
      ...otherRequest,
    };
    if (request?.createTime) {
      const [createTimeStart, createTimeEnd] = request.createTime;
      request['createTimeStart'] = createTimeStart.format('YYYY-MM-DD 00:00:00');
      request['createTimeEnd'] = createTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['createTime'];
    }

    if (request?.cancelTime) {
      const [cancelTimeStart, cancelTimeEnd] = request.cancelTime;
      request['cancelTimeStart'] = cancelTimeStart.format('YYYY-MM-DD 00:00:00');
      request['cancelTimeEnd'] = cancelTimeEnd.format('YYYY-MM-DD 23:59:59');
      delete request['cancelTime'];
    }

    delete request['createFormNameDept'];
    delete request['createFormNameUser'];
    if (request?.createrID && request?.createrID?.length > 0) {
      request['createrID'] = request?.createrID?.toString();
    } else {
      delete request['createrID'];
    }

    run({
      ...request,
    });
  };

  /** 搜索列表  */
  const searchList = useMemo(() => {
    return {
      searchList: searchListParams,
    };
  }, [loadMdicMapObj?.loadMapInfo]);

  /** 页面列表 */
  const returnTableProps = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  return {
    loading,
    getChildManage,
    ...returnTableProps,
    ...searchList,
  };
};

export { contractManageService, contractChildervice };
